<template>
  <editDialog
    :centerDialogVisible="visible"
    :tilte="info && info.typeId ? '编辑问题类型' : '新增问题类型'"
    :key="timer"
    @Cancel="handleCancel"
    @Submit="handleSubmit(ruleFormRef)"
  >
    <!-- 对话框内容 -->
    <template #content>
      <el-form
        label-width="100px"
        :model="form"
        :rules="rules"
        ref="ruleFormRef"
        status-icon
      >
        <el-form-item label="设备类型" prop="DeviceType">
          <el-tree-select
            v-model="form.DeviceType"
            :data="props.filters"
            :render-after-expand="false"
            :disabled="props.disabled"
            placeholder="请选择"
            style="width: 90%"
          />
        </el-form-item>
        <el-form-item label="问题类型" prop="proType">
          <el-input
            v-model="form.proType"
            style="width: 90%"
            onkeyup="value=value.replace(/\s+/g,'')"
          />
        </el-form-item>
        <el-form-item label="所属单位" prop="oragan">
          <el-tree-select
            v-model="form.oragan"
            :data="props.organInfo"
            :render-after-expand="false"
            :disabled="props.disabled"
            placeholder="请选择"
            style="width: 90%"
          />
        </el-form-item>
        <el-form-item label="创建人" v-if="info">
          <el-input
            v-model="form.creator"
            :disabled="props.disabled"
            style="width: 90%"
          />
        </el-form-item>
        <el-form-item label="创建时间" v-if="info">
          <el-input
            v-model="form.times"
            :disabled="props.disabled"
            style="width: 90%"
          />
        </el-form-item>
      </el-form>
    </template>
  </editDialog>
</template>
<script lang="ts" setup>
import {
  ref,
  reactive,
  defineProps,
  defineEmits,
  watch,
  nextTick,
  toRaw,
} from "vue";
import editDialog from "@/components/editDialog/index.vue";
import type { FormInstance, FormRules } from "element-plus";

const ruleFormRef = ref<FormInstance>();

const props = defineProps({
  // 弹窗是否显示
  visible: {
    type: Boolean,
    default: false,
  },
  info: {
    type: Object,
    default: () => null,
  },
  // 弹窗标题
  title: {
    type: String,
    default: "",
  },
  // 设备类型
  filters: {
    type: Array,
    default: () => null,
  },
  organInfo: {
    type: Array,
    default: () => null,
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  timer: {
    type: Number,
    default: null,
  },
});

const emit = defineEmits(["cancel", "ok"]);
// const disabled = ref(false);
const form = reactive({
  DeviceType: "",
  proType: "",
  oragan: "",
  creator: "",
  times: "",
});
(function show() {
  console.log(props.info);
  if (props.info) {
    const info = toRaw(props.info);
    form.DeviceType = info.typeName;
    form.proType = info.problemType;
    form.oragan = info.owner.name;
    form.times = info.createTime;
    form.creator = info.creator.name;
  } else {
    form.DeviceType = "";
    form.proType = "";
    form.oragan = "";
    form.times = "";
    form.creator = "";
  }
})();

const DeviceTypePass = (rule: any, value: any, callback: any) => {
  if (rule) {
    // console.log(value);

    if (value === "") {
      callback(new Error("请选择一个设备类型"));
    } else {
      callback();
    }
  }
};

const oraganPass = (rule: any, value: any, callback: any) => {
  if (rule) {
    // console.log(value);

    if (value === "") {
      callback(new Error("请选择一个所属单位"));
    } else {
      callback();
    }
  }
};

/**
 * 表单校验
 */
const rules = reactive<FormRules>({
  DeviceType: [
    { required: true, validator: DeviceTypePass, trigger: "blur" },
    { required: true, validator: DeviceTypePass, trigger: "change" },
  ],
  proType: [
    {
      required: true,

      message: "请输入问题类型",
      trigger: "blur",
    },
    { required: true, message: "请输入问题类型", trigger: "change" },
    { max: 50, message: "问题类型不能超过50个字", trigger: "blur" },
  ],
  oragan: [
    { required: true, validator: oraganPass, trigger: "blur" },
    { required: true, validator: oraganPass, trigger: "change" },
  ],
});

/**
 * 点击确定
 */

const handleSubmit = async (formEl: FormInstance | undefined) => {
  const newproType = form.proType.replace(/\s+/g, "");
  await nextTick(() => {
    form.proType = newproType;
    console.log(form.proType);
  });
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      emit("ok", form, props.info, oraganName.value);
    } else {
      // console.log("error submit!");
      return false;
    }
  });
};

const handleCancel = () => {
  form.DeviceType = "";
  form.proType = "";
  form.oragan = "";
  form.times = "";
  form.creator = "";
  emit("cancel");
};

// 封装一个递归调用的方法
const findChildren = (data: any, ch: any, n: any) => {
  const result = ref<any>([]);
  data.forEach((item: any) => {
    if (item.value === n) {
      ch.value = item.label;
    } else if (item.children && item.children.length > 0) {
      const childrenResult = findChildren(item.children, ch, n);
      if (childrenResult.length > 0) {
        result.value = childrenResult;
      }
    }
  });
  return result;
};

const label = ref("");
// 监听typeList值的变化，并未label赋值
watch(
  () => form.DeviceType,
  (newVal) => {
    findChildren(props.organInfo, label, newVal);
  }
);
// 监听value1值的变化，并未label1赋值
const oraganName = ref("");
watch(
  () => form?.oragan,
  (newVal) => {
    findChildren(props.organInfo, oraganName, newVal);
  }
);
</script>
